package oakclub.model;

import oakclub.entity.NotificationEntity;
import oakclub.entity.PhotoEntity;
import oakclub.entity.TokenEntity;
import oakclub.entity.UserEntity;
import oakclub.jooq.Tables;
import oakclub.jooq.tables.ChatRosters;
import oakclub.jooq.tables.NotchatMutualmatch;
import oakclub.jooq.tables.Users;
import org.jooq.DSLContext;
import org.jooq.Record;

public class NotificationModel extends BaseModel
{
    public NotificationEntity get(long userId, long targetId) throws Exception
    {
        return (NotificationEntity) this.fetch(new IFetch()
        {
            @Override
            public Object fetch(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                long targetId = (long) params[1];

                // table alias
                Users U = Tables.USERS;
                ChatRosters CR = Tables.CHAT_ROSTERS;
                NotchatMutualmatch NCMM = Tables.NOTCHAT_MUTUALMATCH;

                // user info
                Record userRecord = context
                    .select(U.NAME, U.AVATAR)
                    .from(U)
                    .where(U.USER_ID.eq(userId))
                    .limit(1)
                    .fetchOne();

                // token info
                Record tokenRecord = context
                    .select(U.DEVICE_TOKEN, U.ANDROID_TOKEN)
                    .from(U)
                    .where(U.USER_ID.eq(targetId))
                    .limit(1)
                    .fetchOne();

                // badge
                int badge = context
                    .select(CR.TARGET_ID.as("target_id"))
                    .from(CR)
                    .where(CR.USER_ID.eq(targetId))
                    .union(context
                        .select(NCMM.TARGET_ID.as("target_id"))
                        .from(NCMM)
                        .where(NCMM.USER_ID.eq(targetId)))
                    .fetchCount();

                // parse
                NotificationEntity notification = new NotificationEntity();
                notification.setUser(new UserEntity());
                notification.setToken(new TokenEntity(tokenRecord.getValue(U.DEVICE_TOKEN), tokenRecord.getValue(U.ANDROID_TOKEN)));
                notification.setBadge(badge);

                UserEntity user = notification.getUser();
                user.setId(userId);
                user.setName(userRecord.getValue(U.NAME));
                user.setAvatar(new PhotoEntity(user, userRecord.getValue(U.AVATAR)));

                return notification;
            }
        }, userId, targetId);
    }
}
